using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using CloudShot.Editor.CanvasFigures;
using CloudShot.Entities;
using CloudShot.Logic;
using CloudShot.Utils;

namespace CloudShot.Editor.Tools.States
{
  internal class MoveObjectState : IPointerToolState
  {
    private readonly IDrawingCanvas _canvas;
    private readonly ICursorService _cursorService;
    private Point _lastPoint;

    public MoveObjectState(IDrawingCanvas canvas, ICursorService cursorService, CanvasObject canvasObject, Point lastPoint)
    {
      _canvas = canvas;
      _cursorService = cursorService;

      bool isModifierPressed = _canvas.IsAnyModifierPressed(KeyModifiers.Ctrl | KeyModifiers.Shift);

      if (isModifierPressed)
      {
        canvasObject.IsSelected = !canvasObject.IsSelected;//invert selection if modifier pressed and we click on selected object
      }
      else
      {
        if (!canvasObject.IsSelected)
        {
          _canvas.GraphicsList.DeselectAll(); //deselect all objects and we will select current object below  
          canvasObject.IsSelected = true;//select object if modifier not pressed
        }        
      }

      _cursorService.Cursor = AppCursors.FigureDragCursor;
      _lastPoint = lastPoint;
    }

    #region IPointerToolState Members

    public void OnMouseMove(Point point)
    {
      int dx = point.X - _lastPoint.X;
      int dy = point.Y - _lastPoint.Y;

      _lastPoint.X = point.X;
      _lastPoint.Y = point.Y;

      var selectedObjects = _canvas.GraphicsList.SelectedObjects.ToList();

      using (new AutomaticCanvasRefresher(_canvas, selectedObjects.GetGroupBoundingBox))
      {
        foreach (CanvasObject selectionedObject in selectedObjects)
        {
          selectionedObject.Move(dx, dy);
        }
      }

      _cursorService.Cursor = AppCursors.FigureDragCursor;
    }

    public void OnKeyDown(KeyEventArgs keyEventArgs)
    {
      //Empty
    }

    public void OnKeyUp(KeyEventArgs keyEventArgs)
    {
      //Empty
    }

    public void Enter(){}

    public void Release()
    {
      _lastPoint = new Point(0, 0);
    }

    #endregion
  }
}